/**
 * 
 */
package sailing.managers.impl;

import java.util.List;

import cjlite.annotations.Inject;
import cjlite.utils.Lists;
import cjlite.utils.Strings;
import sailing.dao.CustomerDao;
import sailing.entity.Customer;
import sailing.managers.CustomerManager;

/**
 * @author kevin
 * 
 */
public class CustomerManagerImpl implements CustomerManager {

	private List<Customer> customerList = Lists.newArrayList();

	@Inject
	private CustomerDao cDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.managers.CustomerManager#save(sailing.entity.Customer)
	 */
	@Override
	public String save(Customer c) {
		if (isExistForNew(c)) {
			return Strings.concat("客户【", c.getName(), "】已经存在，请重新输入客户名字");
		}
		if (cDao.save(c)) {
			return "";
		}
		return "添加失败！";
	}

	private boolean isExistForNew(Customer c) {
		for (Customer exist : customerList) {
			if (exist.getName().equals(c.getName())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<Customer> getAllCustomerList() {
		List<Customer> clist = cDao.getAllList();
		if (clist == null) {
			return Lists.newArrayList();
		}
		customerList.clear();
		customerList.addAll(clist);
		return clist;
	}

	@Override
	public void delete(Customer cc) {
		boolean result = cDao.delete(cc);
	}

	@Override
	public String update(Customer editCustomer) {
		for (Customer cc : customerList) {
			if (cc.getName().equals(editCustomer.getName()) && !cc.getId().equals(editCustomer.getId())) {
				return Strings.concat("客户【", editCustomer.getName(), "】已经存在，请重新输入客户名字");
			}
		}
		if (cDao.update(editCustomer)) {
			return "";
		}
		return "保存数据失败！";
	}

}
